import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, InputNumber, TreeSelect } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { deptUpdate, deptDetail, deptpage } from '@/services/system/departmentmanage';
import CustomPageContainer from '@/components/CustomPageContainer';
import { useModel } from '@umijs/max';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
  },
  formContainer: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '24px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  formItem: {
    marginBottom: '16px',
    '& .ant-form-item-label': {
      fontWeight: 500,
      color: '#333',
    },
    '& .ant-input': {
      borderRadius: '4px',
      '&:focus': {
        borderColor: '#1890ff',
        boxShadow: '0 0 0 2px rgba(24, 144, 255, 0.2)',
      },
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

interface DeptTreeItem {
  id: number;
  departmentId: string;
  deptName: string;
  fullName: string;
  deptCategory: number;
  parementId: string | null;
  ancestors: string;
  children?: DeptTreeItem[];
  isDeleted: number;
  remark: string;
  sort: number;
}

interface TreeDataNode {
  title: string;
  value: number | string;
  key: number | string;
  children?: TreeDataNode[];
}

const DepartmentEdit: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const [deptTreeData, setDeptTreeData] = useState<DeptTreeItem[]>([]);
  const [loading, setLoading] = useState(false);
  const { institutionId, institutionRoleId } = useModel('auth');

  const departmentId = location.state?.record?.departmentId;

  useEffect(() => {
    if (departmentId) {
      fetchData();
    }
  }, [departmentId]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [detailRes, treeRes] = await Promise.all([
        deptDetail({ departmentId: departmentId }),
        deptpage({
          institutionId: institutionId,
          institutionRoleId: institutionRoleId,
        })
      ]);

      if (detailRes.code === 200 && detailRes.success) {
        form.setFieldsValue({
          deptName: detailRes.data.deptName,
          deptCategory: detailRes.data.deptCategory,
          parementId: detailRes.data.parementId || '',
          sort: detailRes.data.sort,
          remark: detailRes.data.remark,
        });
      } else {
        message.error('获取部门详情失败');
        navigate('/system/departmentmanage');
      }

      if (treeRes.code === 200 && treeRes.success) {
        setDeptTreeData(treeRes.data);
      } else {
        message.error('获取部门列表失败');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      navigate('/system/departmentmanage');
    } finally {
      setLoading(false);
    }
  };

  const convertToTreeData = (deptList: DeptTreeItem[]): TreeDataNode[] => {
    return deptList.map(dept => ({
      title: dept.deptName,
      value: dept.departmentId,
      key: dept.departmentId,
      children: dept.children ? convertToTreeData(dept.children) : undefined
    }));
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const response = await deptUpdate({
        ...values,
        departmentId: departmentId,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      });

      if (response.code === 200) {
        message.success('修改部门成功');
        navigate('/system/departmentmanage');
      } else {
        message.error(response.msg || '修改部门失败');
      }
    } catch (error) {
      console.error('修改失败:', error);
      message.error('修改部门失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <CustomPageContainer>
      <Card className={styles.card} loading={loading}>
        <div className={styles.formContainer}>
          <div className={styles.title}>部门修改</div>
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
          >
            <Form.Item
              label="部门名称"
              name="deptName"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入部门名称' }]}
            >
              <Input placeholder="财务部" />
            </Form.Item>

            <Form.Item
              label="部门类型"
              name="deptCategory"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择部门类型' }]}
            >
              <Select placeholder="请选择部门类型">
                <Select.Option value={1}>部门</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="上级部门"
              name="parementId"
              className={styles.formItem}
              rules={[{
                required: true,
                message: '请选择上级部门',
                validator: (_, value) => {
                  if (value === '' || value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('请选择上级部门'));
                }
              }]}
            >
              <TreeSelect
                placeholder="请选择上级部门"
                allowClear
                showSearch
                treeDefaultExpandAll
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={[
                  { title: '顶级', value: '', key: '0' },
                  ...convertToTreeData(deptTreeData)
                ]}
                treeNodeFilterProp="title"
              />
            </Form.Item>

            <Form.Item
              label="部门排序"
              name="sort"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入部门排序' }]}
            >
              <InputNumber min={1} style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              label="部门备注"
              name="remark"
              className={styles.formItem}
            >
              <Input.TextArea
                rows={4}
                placeholder="该部门属于xxxx运营公司财务部门。"
              />
            </Form.Item>

            <div className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => navigate('/system/departmentmanage')}
              >
                返回
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                className={styles.button}
              >
                确定
              </Button>
            </div>
          </Form>
        </div>
      </Card>
    </CustomPageContainer>
  );
};

export default DepartmentEdit;
